package fr.emse.tatiana.scoresheetvisualisation;

import org.eclipse.draw2d.ColorConstants;
import org.eclipse.draw2d.Ellipse;
import org.eclipse.draw2d.Figure;
import org.eclipse.draw2d.LineBorder;
import org.eclipse.draw2d.Shape;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.swt.graphics.Color;

import fr.emse.tatiana.graphical.IRuleableFigure;


public class EventFigure extends Figure implements IRuleableFigure {
	
	private boolean hasshape=false;
	
	boolean visible;
	Color bg;
	Color border;
	Rectangle r;
	Shape shape;
	
	public EventFigure() {
		//setLayoutManager(new XYLayout());
		
		if (hasshape) {
			shape = new Ellipse();
			this.add(shape);
		}
		setOpaque(true); // this seems to cause problems with drawing subfigures. Try adding it to setShape
		//set a bunch of defaults
		r = new Rectangle();
		this.setBorder(new LineBorder(0));
		border = ColorConstants.black;
	}

	private void doUpdateBounds() {
		int h = r.height;
		int w = r.width+(hasshape?h/2:0);
		if (hasshape && w<h) w = h;
		int x = r.x - (hasshape? h/2:0);
		int y = r.y - h/2;
		setBounds(new Rectangle(x,y,w,h));
		if (hasshape) {
			this.setBounds(getBounds().expand(1, 1));
			shape.setBounds(new Rectangle(x,y,h,h));
		}
	}
	
	public void setHeight(int h) {
		r.setSize(r.getSize().width, h);
		doUpdateBounds();
	}
	
	public void setWidth(int w) {
		r.setSize(w, r.getSize().height);
		doUpdateBounds();
	}
	
	public void setAbsoluteY(int y) {
		r.setLocation(r.getLocation().x, y);
		doUpdateBounds();
	}
	
	public void setAbsoluteX(int x) {
		r.setLocation(x, r.getLocation().y);
		doUpdateBounds();
	}
	
	public void moveY(int dy) {
		setAbsoluteY(r.getLocation().y+dy);
	}
	
	@Override
	public void setVisible(boolean visible) {
		this.visible = visible;
		super.setVisible(visible);
		if (hasshape) {
			shape.setVisible(visible);
		}
	}
	
	@Override
	public void setBackgroundColor(Color c) {
		this.bg = c;
		if (hasshape) {
			shape.setBackgroundColor(c);
		} else {
			super.setBackgroundColor(c);
		}
	}
	
	public void setBorderColor(Color c) {
		this.border = c;
		//if (hasshape) {
			this.setForegroundColor(c);
		//} else {
			//super.setBorder(new LineBorder(c));
		//}
		
	}
	
	public void setShape(Shape shape) {
		if (shape==null && hasshape) {
			hasshape = false;
			//this.shape.setVisible(false);
			this.remove(this.shape);
			this.shape = null;
			super.setBorder(new LineBorder(this.border));
			super.setBackgroundColor(this.bg);
			super.setVisible(this.visible);
			doUpdateBounds();
		} else if (shape != null) {
			if (hasshape) {
				this.remove(this.shape);
			}
			this.hasshape = true;
			this.shape = shape;
			this.add(shape);
			//shape.setBorder(new LineBorder(this.border));
			shape.setBackgroundColor(this.bg);
			shape.setVisible(this.visible);
			super.setBorder(new LineBorder(ColorConstants.white));
			super.setBackgroundColor(ColorConstants.white);
			doUpdateBounds();
		}
	}
	// have methods that override the defaults
	
}